package com.nowcoder.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectById;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.mapper.DiscussPostMapper;
import com.nowcoder.community.service.IDiscussPostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.RedisKeyUtil;
import com.nowcoder.community.util.SensitiveFilter;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 朱哥
 * @since 2025-02-13
 */
@Service
public class DiscussPostServiceImpl extends ServiceImpl<DiscussPostMapper, DiscussPost> implements IDiscussPostService, CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(DiscussPostServiceImpl.class);

    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${caffeine.posts.max-size}")
    private int maxSize;

    @Value("${caffeine.posts.expire-seconds}")
    private int expireSeconds;

    // Caffeine核心接口: Cache, LoadingCache, AsyncLoadingCache

    // 帖子列表缓存
    private LoadingCache<String, List<DiscussPost>> postListCache;

    // 帖子总数缓存
    private LoadingCache<Integer, Integer> postRowsCache;

    @PostConstruct
    public void init() {
        // 初始化帖子列表缓存
        postListCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<String, List<DiscussPost>>() {  //传一个接口，匿名实现。如果缓存中没有这个数据，想办法把这个数据装到缓存里
                    @Nullable
                    @Override
                    public List<DiscussPost> load(@NonNull String key) throws Exception {
                        if (key == null || key.length() == 0) {
                            throw new IllegalArgumentException("参数错误!");
                        }

                        String[] params = key.split(":");
                        if (params == null || params.length != 2) {
                            throw new IllegalArgumentException("参数错误!");
                        }

                        int offset = Integer.valueOf(params[0]);
                        int limit = Integer.valueOf(params[1]);

                        // 二级缓存: Redis -> mysql
                        String redisKey = RedisKeyUtil.getHotPostKey(offset,limit);

                        // 1. 先查 Redis
                        List<DiscussPost> list = (List<DiscussPost>) redisTemplate.opsForValue().get(redisKey);
                        if (list != null) {
                            logger.debug("load post list from Redis.");
                            return list;
                        }

                        // 2. Redis 没有，查数据库
                        logger.debug("load post list from DB.");
                        list = discussPostMapper.selectDiscussPosts(0, offset, limit, 1);

                        // 3. 把结果写回 Redis（再回源给 Caffeine）
                        redisTemplate.opsForValue().set(redisKey, list, HOT_POST_EXPIRED_SECONDS, TimeUnit.SECONDS);
                        return list;
                    }
                });
        // 初始化帖子总数缓存
        postRowsCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<Integer, Integer>() {
                    @Nullable
                    @Override
                    public Integer load(@NonNull Integer key) throws Exception {
                        // 1. 拼 Redis key
                        String redisKey = RedisKeyUtil.getPostRows();

                        // 2. 先读 Redis
                        Integer rows = (Integer) redisTemplate.opsForValue().get(redisKey);
                        if (rows != null) {
                            logger.debug("load post rows from Redis.");
                            return rows;
                        }

                        // 3. Redis 没有，读 DB
                        logger.debug("load post rows from DB.");
                        rows = discussPostMapper.selectDiscussPostRows(key);

                        // 4. 写回 Redis，比本地缓存时间略长
                        redisTemplate.opsForValue()
                                .set(redisKey, rows,
                                        HOT_POST_EXPIRED_SECONDS, TimeUnit.SECONDS);

                        return rows;
                    }
                });
    }
    @Override
    public List<DiscussPost> findDisscussPosts(int userId, int offset, int limit, int orderMode) {
        if (userId == 0 && orderMode == 1) {
            return postListCache.get(offset + ":" + limit);
        }

        logger.debug("load post list from DB.");
        return discussPostMapper.selectDiscussPosts(userId,offset,limit,orderMode);
    }

    @Override
    public void addDisCussPost(DiscussPost post) {
        if (post == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        // 转义HTML标记
        post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));//用springMVC为我们提供工具来帮我们转义><
        post.setContent(HtmlUtils.htmlEscape(post.getContent()));
        // 过滤敏感词
        post.setTitle(sensitiveFilter.filter(post.getTitle()));
        post.setContent(sensitiveFilter.filter(post.getContent()));
        discussPostMapper.insert(post);
    }

    @Override
    public DiscussPost findDiscussPostById(int discussPostId) {
        DiscussPost post = discussPostMapper.selectById(discussPostId);
        return post;
    }

    public int findDisscussPostsRows(int userId){
        if (userId == 0) {
            return postRowsCache.get(userId);
        }

        logger.debug("load post rows from DB.");
        return discussPostMapper.selectDiscussPostRows(userId);
//        QueryWrapper<DiscussPost> queryWrapper = new QueryWrapper<>();
//        queryWrapper.ne("status", 2);
//        if (userId != 0) {
//            queryWrapper.eq("user_id", userId); // 等价于 where user_id = #{userId}
//        }
//        return Math.toIntExact(baseMapper.selectCount(queryWrapper));
    }

    @Override
    public int updateType(int id, int type) {
        return discussPostMapper.updateType(id, type);
    }

    @Override
    public int updateStatus(int id, int status) {
        return discussPostMapper.updateStatus(id, status);
    }

    @Override
    public int updateScore(int id, double score) {
        return discussPostMapper.updateScore(id, score);
    }

}
